package com.qf.dao.impl;

import com.qf.dao.CartDao;
import com.qf.domain.Cart;
import com.qf.util.DataSourceUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class CartDaoImpl implements CartDao {
    private QueryRunner queryRunner = new QueryRunner(DataSourceUtil.getDataSource());//数据源
    @Override
    public void insert(Cart cart) {
    String sql="insert into tb_cart (id,pid,num,money) values (?,?,?,?)";
    Object [] params={cart.getId(),cart.getPid(),cart.getNum(),cart.getMoney()};
        try {
            queryRunner.update(sql,params);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Override
    public Cart select(Integer uid, int goods_id) {
        String sql="select * from tb_cart where id=? and pid=?";
        try {
            return queryRunner.query(sql,new BeanHandler<>(Cart.class),uid,goods_id);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Override
    public void update(Cart cart) {
        String sql="update tb_cart set num=?,money=? where id=? and pid=?";
        Object[]params={cart.getNum(),cart.getMoney(),cart.getId(),cart.getPid()};
        try {
            queryRunner.update(sql,params);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Cart> select(Integer uid) {
        String sql="select * from tb_cart where id=?";
        try {
            return queryRunner.query(sql,new BeanListHandler<>(Cart.class),uid);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Override
    public void delete(Integer uid, int goods_id) {
        String sql="delete from tb_cart where id=? and pid=?";
        try {
            queryRunner.update(sql,uid,goods_id);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteAll(Integer uid) {
        Connection conn = DataSourceUtil.getConnection();
        try {
            QueryRunner qr = new QueryRunner();
            qr.update(conn,"delete from tb_cart where id=?",uid);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }finally {
            DataSourceUtil.closeAll(null,null,conn);
        }
    }
}
